from machine import Pin,I2C,SoftI2C
import framebuf
import ufont

from setcfg import DAT
print("初始化OLED屏幕总线 scl=%d,sda=%d,type=%s"%(DAT['oled']['scl'],DAT['oled']['sda'],DAT['oled']['type']))

try:
  i2c=SoftI2C(scl=Pin(DAT['oled']['scl']),sda=Pin(DAT['oled']['sda']))
except:
  print("初始化OLED的I2C失败")
  
 
oled=None
font=None
# 定义全局变量 g_status
g_status = 0

def Sleep(sleepStatus):
  if g_status==0:return
  oled.sleep(sleepStatus)

def init(rotate=180, oledtype=DAT['oled']['type']):
    global oled, font, g_status,i2c  # 确保 g_status 是全局变量
    try:
        if oledtype == "sh1106":
            from sh1106 import SH1106_I2C
            oled = SH1106_I2C(128, 64, i2c, rotate=180)
        else:
            from ssd1306 import SSD1306_I2C            
            i2c=SoftI2C(scl=Pin(DAT['oled']['scl']),sda=Pin(DAT['oled']['sda']))
            oled = SSD1306_I2C(128, 64, i2c)

        font = ufont.BMFont("oled/unifont-14-12917-16.v3.bmf")
        g_status = 1  # 更新 g_status 为 1
        Sleep(False)
        print("OLED初始化成功")
    except Exception as e:
        print("屏幕驱动加载失败:"+str(e))
        g_status = 0  # 更新 g_status 为 0


def text(str,x,y,color):
  if g_status==0:return
  font.text(oled,str,x, y,color,show=True,auto_wrap=True)
  
def image(img,x,y):
  if g_status==0:return
  oled.blit(img,x,y)

def fill(value):
  if g_status==0:return
  oled.fill(value)
  
def show():
  if g_status==0:return
  oled.show()
  
def text_direct(str,x=0,y=0,color=1):
  if g_status==0:return
  fill(0)
  text(str,x,y,color)
  show()

def arraytobuff(arr):
  return framebuf.FrameBuffer(arr, 128, 64, framebuf.MONO_VLSB)

def image_direct(img,x=0,y=0):
  if g_status==0:return
  fill(0)
  image(arraytobuff(img),x,y)
  show()


  
